*** Creates
* "data_YLE_wide.dta" (extended dataset)
* "data_YLE_main.dta" (long dataset)
*** from 
* "data_src_YLE_merged_wide_anom.dta" (wide merged YLE data)
* "data_src_munidata_12_17.dta"

* CHANGE THIS

cd /path/to/directory

clear

use "data_src_YLE_merged_wide_anom.dta"

gen firstdiff = refugees2017 - refugees2012

gen loser = 0
replace loser = 1 if elected2012 == 0

gen spare = 0
replace spare = 1 if elected2012 == 0.5

gen incumbent = 0
replace incumbent = 1 if elected2012 == 1

gen rantwice = 0
replace rantwice = 1 if (!missing(votes2012) & !missing(votes2017))

gen answeredtwice = 0
replace answeredtwice = 1 if (!missing(refugees2012) & !missing(refugees2017))

*** before reshaping save this for future use: 

save "data_YLE_wide.dta", replace

reshape long votes voteshare age elected environment refugees urban population ///
    , i(seqnum) j(year) string

*** merging with covariates ***

destring year, replace

merge m:1 muni year using "data_src_munidata_12_17.dta", force

*** drop not used ones: 

drop betwee_15_64 over_64 birth_surplus nro_of_families nro_households ///
    nro_households nro_private_houses nro_rentals secondary_educ employment ///
    non_commuters share_of_pensioners nro_of_jobs agriculture industry service ///
    culture_educ social_health _merge

rename share_of_foreigners foreigners
rename popchange changeinpop
rename higher_educ highereduc

rename seqnum CandidateID

replace firstdiff = . if year == 2012

gen treat = 0

replace treat = 1 if (year == 2017 & Treated2015 == 1)

replace incumbent = 0 if year == 2012
replace spare     = 0 if year == 2012
replace loser     = 0 if year == 2012

save "data_YLE_main.dta", replace

*******************************************************************************
